import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/modules/user'

const routes = [
  {
    path: '/',
    redirect: '/login',
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/page/login/login.vue'),
  },
  {
    path: '/index',
    name: 'index',
    component: () => import('@/page/index/index.vue'),
    redirect: '/daily-recom',
    children: [
      {
        //数据分析
        path: '/analysis',
        name: 'analysis',
        component: () => import('@/page/data-analysis/index.vue'),
      },
      {
        //每日推荐
        path: '/daily-recom',
        name: 'daily-recom',
        component: () => import('@/page/daily-recom/index.vue'),
      },
      {
        //每日推荐-上传
        path: '/daily-recom-upload',
        name: 'daily-recom-upload',
        component: () => import('@/page/daily-recom/upload.vue'),
      },
      {
        //推荐游记
        path: '/reco-travel',
        name: 'reco-travel',
        component: () => import('@/page/reco-travel/index.vue'),
      },
      {
        //推荐游记-上传
        path: '/reco-travel-upload',
        name: 'reco-travel-upload',
        component: () => import('@/page/reco-travel/upload.vue'),
      },
      {
        //游记管理
        path: '/travel-manag',
        name: 'travel-manag',
        component: () => import('@/page/travel-manag/index.vue'),
      },
      {
        //用户管理
        path: '/user-manag',
        name: 'user-manag',
        component: () => import('@/page/user-manag/index.vue'),
      },
      {
        //后台设置
        path: '/back-setting',
        name: 'back-setting',
        component: () => import('@/page/back-setting/index.vue'),
      },
    ],
  },
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
})

// 全局前置守卫：基于 user_Token 进行登录校验
router.beforeEach((to, _from, next) => {
  const userStore = useUserStore()
  const token = userStore.userInfo?.user_Token
  const whiteList = ['/login']

  if (token) {
    // 已登录访问登录页，重定向到首页
    if (to.path === '/login') {
      next('/index')
    } else {
      next()
    }
  } else {
    // 未登录仅允许访问白名单
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
